package com.itic.appbase.applications.sys.mobilelog.controller;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.ReflectHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.applications.sys.mobilelog.persistence.model.MobileLog;
import com.itic.appbase.applications.sys.mobilelog.persistence.model.MobileLogExample;
import com.itic.appbase.applications.sys.mobilelog.persistence.model.MobileLogExample.Criteria;
import com.itic.appbase.applications.sys.mobilelog.service.MobileLogService;


@Controller
@RequestMapping(value="/sys/mobilelog")
public class MobileLogController
     extends BaseController {
    @Autowired
    private MobileLogService mobileLogService;


    // 返回属性黑名单
    //private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "createTime", "updateTime", "orgCode" };

    /**
     * 跳转到主页面
     * 
     * @return String
     */
    @RequestMapping("/init")
    public String init() {
        return "sys/mobilelog/mobileLogMain";
    }


    /**
     * 跳转到主页面
     * 
     * @return String
     */
    @RequestMapping("/initView")
    public String initView(String id,Model model) {
    	if(StringHelper.isNotBlank(id)){
    		MobileLog mobileLog  = mobileLogService.get(id);
    		model.addAttribute(mobileLog);
    	}else {
            throw new ParameterErrorException();
        }
        return "sys/mobilelog/mobileLogView";
    }
    

    /**
     * 查询日志列表
     * 
     * @param request
     * @param sysLog
     * @return Map
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> getLogList(HttpServletRequest request, MobileLog mobileLog) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String startTime = this.getCleanParams(request, "startTime");
        String endTime = this.getCleanParams(request, "endTime");

        // 封装查询条件
        MobileLogExample example = new MobileLogExample();
        example = this.handlePageQuery(request, example);
        example.setOrderByClause("CREATE_TIME DESC");

        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != mobileLog) {
            if (StringHelper.isNotBlank(mobileLog.getRequestParam())) {
                criteria.andRequestParamLike("%" + mobileLog.getRequestParam() + "%");
            }

            if (StringHelper.isNotBlank(mobileLog.getResponseData())) {
                criteria.andResponseDataLike("%" + mobileLog.getResponseData() + "%");
            }

            //时间查询
            if (StringHelper.isNotBlank(startTime)) {
                criteria.andCreateTimeGreaterThanOrEqualTo(this.fixStartTime(startTime));
            }
            if (StringHelper.isNotBlank(endTime)) {
                criteria.andCreateTimeLessThanOrEqualTo(this.fixEndTime(endTime));
            }
        }

        Integer total = mobileLogService.count(example);
        List<MobileLog> logList = mobileLogService.list(example);
        if( logList.size() > 0 ){
        	for( MobileLog tmp : logList ){
        		if( tmp.getResponseData().contains("html") ){
        			tmp.setResponseData("这返回的是JSP页面啊");
        		}
        	}
        }
        //List<Map<String, Object>> resultList = ValueHelper.tranList2MapList(logList, ignoreProperties);
       
        resultMap.put(IticConst.TOTAL_RECORDS, total); // 总数，显示总数量
        resultMap.put(IticConst.DISPLAY_RECORDS, total); // 显示display中的总数量
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode()); // 返回结果
        resultMap.put(IticConst.DATA, logList); // 返回值
        return resultMap;
    }

    /**
     * 删除日志
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, String> delete(String ids) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if (StringHelper.isNotBlank(ids)) {
            MobileLogExample example = new MobileLogExample();
            List<String> logIdList = Arrays.asList(ids.split(","));
            example.createCriteria().andIdIn(logIdList);
            MobileLog sysLog = new MobileLog();
            sysLog.setUpdateTime(new Date());
            sysLog.setIsEffective(DBConst.FALSE);
            result = mobileLogService.deleteByExample(sysLog, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

 public void add(HttpServletRequest request,HttpServletResponse response) {
    	
        String url = request.getRequestURI().replace(request.getContextPath(), "");
        String token = request.getParameter("token");
        MobileLog log = new MobileLog();
        //User user = this.findUserSession(request);
    	log.setIp(this.toIpAddr(request));
    	log.setUrl(url);
    	log.setStatus( response.getStatus()+"" );//请求状态
    	log.setUserName(token);
        
    	log.setRequestParam( JSONObject.fromObject(request.getParameterMap()).toString() );//请求参数
        //sysMobileLog.setOrgname(innerCommonService.getOrgByCode(user.getOrganizationCode()).getName());
    	log.setResponseData( getResponseResult(response).toString() );//返回result
        //sysMobileLog.setOrgname("unknown");
        //sysMobileLog.setCreateUser(user.getId());
        //sysMobileLog.setOrgCode(user.getOrganizationCode());
        mobileLogService.add(log);
        
    }
    
    public Object getResponseResult( HttpServletResponse response ){
    	Object valueByFieldName = ReflectHelper.getValueByFieldName(response, "response");
    	System.out.println(valueByFieldName);
    	Object t = ReflectHelper.getValueByFieldName(valueByFieldName, "response");
    	System.out.println(t);
    	Object t1 = ReflectHelper.getValueByFieldName(t, "outputBuffer");
    	System.out.println(t1);
    	
    	Object t2 = ReflectHelper.getValueByFieldName(t1, "outputChunk");
    	return t2;
    }

}